// 打家劫舍问题

// F(n) = max(F(n-2) + An, F(n-1))

var rob = function (nums) {
    if (nums.length < 1) return 0
    if (nums.length === 1) {
        return nums[0]
    } else if (nums.length === 2) {
        return Math.max(nums[0], nums[1])
    } else if (nums.length > 2) {
        const dp = [nums[0], Math.max(nums[0], nums[1])]
        for (let i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i -1])  // 注意这里
        }
        console.log(dp)
        return dp[nums.length - 1]
    }
}

// 不使用数组
const rob1 = function (nums) {
    if (nums.length < 1) return 0
    if (nums.length === 1) {
        return nums[0]
    } else if (nums.length === 2) {
        return Math.max(nums[0], nums[1])
    } else if (nums.length > 2) {
        // const dp = [nums[0], Math.max(nums[0], nums[1])]
        let dp0 = nums[0], dp1 = Math.max(nums[0], nums[1])
        for (let i = 2; i < nums.length; i++) {
            let temp = Math.max(dp0 + nums[i], dp1)
            dp0 = dp1
            dp1 = temp
        }
        return dp1
    }
}

const res = rob1([2, 7, 9, 3, 1])
console.log(res)